/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-08-24     yangjie      the first version
 */

/*
 * 程序清单：消息队列例程
 *
 * 这个程序会创建2个动态线程，一个线程会从消息队列中收取消息；一个线程会定时给消
 * 息队列发送 普通消息和紧急消息。
 */
#include <aos/aos.h>
#include "aos/cli.h"
#include <debug/dbg.h>

#define THREAD_PRIORITY      25
#define THREAD_TIMESLICE     5
#define THREAD_STACK_SIZE    2048

/* 消息队列控制块 */
static aos_queue_t queue;
/* 消息队列中用到的放置消息的内存池 */
static unsigned char msg_pool[2048];

/* 线程控制块 */
static aos_task_t tid1 = NULL;
static aos_task_t tid2 = NULL;

/* 线程1入口函数 */
static void thread1_entry(void *parameter)
{
    char buf = 0;
    unsigned char cnt = 0;
    size_t size = sizeof(buf);

    while (1)
    {
        /* 从消息队列中接收消息 */
        if (aos_queue_recv(&queue, AOS_WAIT_FOREVER, &buf, &size) == 0)
        {
            aos_debug_printf("thread1: recv msg from msg queue, the content:%c\n", buf);
            if (cnt == 19)
            {
                break;
            }
        }
        /* 延时50ms */
        cnt++;
        aos_msleep(50);
    }
    aos_debug_printf("thread1: detach mq \n");
    aos_queue_free(&queue);
}

/* 线程2入口 */
static void thread2_entry(void *parameter)
{
    int result;
    char buf = 'A';
    unsigned char cnt = 0;

    while (1)
    {
        if (cnt >= 20)/* 发送20次消息之后退出 */
        {
            aos_debug_printf("message queue stop send, thread2 quit\n");
            break;
        }
        else
        {
            /* 发送消息到消息队列中 */
            result = aos_queue_send(&queue, &buf, 1);
            if (result != 0)
            {
                aos_debug_printf("rt_mq_send ERR\n");
            }

            aos_debug_printf("thread2: send message - %c\n", buf);
        }
        buf++;
        cnt++;
        /* 延时5ms */
        aos_msleep(5);
    }
}

/* 消息队列示例的初始化 */
int yoc_msgq_sample(int argc, char **argv)
{
    aos_status_t result;

    /* 初始化消息队列 */
    result = aos_queue_create(&queue,
                             sizeof(msg_pool),
                             1,
                             0);

    if (result != 0)
    {
        aos_debug_printf("init message queue failed.\n");
        return -1;
    }
    /* 初始化线程 */
    aos_task_create(&tid1,
                    "thread1",
                    thread1_entry, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY,
                    AOS_TASK_AUTORUN);

    aos_task_create(&tid2,
                    "thread2",
                    thread2_entry, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY,
                    AOS_TASK_AUTORUN);

    return 0;
}

/* 导出到 msh 命令列表中 */
ALIOS_CLI_CMD_REGISTER(yoc_msgq_sample, yoc_msgq_sample, yoc msgq sample);

